package cn.edu.zzuli.nothinglink.controller;


import cn.edu.zzuli.nothinglink.anno.CurrentUser;
import cn.edu.zzuli.nothinglink.entity.R;
import cn.edu.zzuli.nothinglink.service.ClassesService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author suzyyy
 * @since 2021-04-08
 */
@RestController
@RequestMapping("/classes")
public class ClassesController {

    @Autowired
    ClassesService classesService;

    @PostMapping("/info")
    public R add(@CurrentUser Integer uId, @RequestBody JSONObject json) {
        if (uId == null) return R.error().add("error", "请登录");
        //这不是很优雅，还是建议搞个vo类来做jsr303校验
        if (json.get("className") != null
                && json.get("college") != null
                && json.get("classSession") != null
                && json.get("classNumber") != null) {
            return classesService.createClass(uId, json);
        }

        return R.error().add("error", "参数有误");
    }

    @GetMapping("/info/list/{type}/{haveDeleted}")
    public R list(@CurrentUser Integer uId,
                  @PathVariable(value = "type") Integer type,
                  @PathVariable(value = "haveDeleted") Integer haveDeleted) {
        if (uId == null) return R.error().add("error", "参数有误");
        return classesService.listClassInfo(uId, type, haveDeleted);
    }

    @GetMapping("/info/{classId}")
    public R getClassInfo(@PathVariable Integer classId) {
        return classesService.getClassInfo(classId);
    }

    @DeleteMapping("/info/{classId}")
    public R deleteClass(@PathVariable Integer classId) {
        if (classesService.removeById(classId)) return R.success();
        return R.error();
    }

    @PutMapping("/bind")
    public R bindClass(@RequestBody JSONObject json, @CurrentUser Integer uId) {
        //学生进行绑定时，通过token来拿uID，老师进行绑定时，通过json数据来获取uID
        Integer stuId = null;

        if (!StringUtils.isEmpty(json.get("url")) ) {
            if (json.getInteger("stuId") != null)
                stuId = json.getInteger("stuId");
            else if (uId != null) stuId = uId;
            else return R.error().add("error", "请检查stuId参数");

            return classesService.bindClassByURL(json.getString("url"),
                    stuId);
        }

        return R.error().add("error", "绑定失败，请检查参数");
    }

}

